import React from "react";
import GoBack from "@/components/TheGoBack";
import {Form, Input, InputNumber, Select, Radio, Divider, Space, Button, Tag, Upload, message} from "antd";
import TheButton from "@/components/TheButton";
import TheUpload from "@/components/TheUpload";
import "../style/style.less";
import {apiGetAdoptClassifyList, apiGetAdoptLabelList, apiGetAdoptAdd} from '@/request/adopt'
import {apiGetGoodsList, apiAdd, apiEdit, apiGetGoodsDetail, apiView} from '@/request/marketingTool'
import moment from "moment/moment";
import {UploadOutlined} from "@ant-design/icons";
const {Option, OptGroup} = Select;

class Add extends React.Component {
    state = {
        goodsList: [],
        productSku: {},
        currentSku: {},
        loading: false,
        fileList: [],
    };

    componentDidMount() {
        this.getData()
    }

    //获取商品列表
    async getData() {
        let res = await apiGetGoodsList()
        if (res.code === 0) {
            this.setState({
                goodsList: res.data
            })
        }
    }

    //选择商品后处理显示数据
    selectFilter(input, option) {
        return option.children.toLowerCase().includes(input.toLowerCase())
    }

    goodsChange(e, row) {
        this.apiGetGoodsDetail(e)
    }

    async apiGetGoodsDetail(goodsId, skuId) {
        let res = await apiGetGoodsDetail({goodsId})
        if (res.code === 0) {
            if (skuId) {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo.filter(item => item.SKUId === skuId)[0]
                })
            } else {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo[0]
                })
            }

        }
    }

    triggerSkuTag(row) {
        // if (this.state.id !== 'null') {
        //   return
        // }
        this.setState({
            currentSku: row
        })
    }

    onFinish(values) {
        let {fileList, currentSku, productSku} = this.state

        // let applyData = {
        //     goodsId: values.goodsId,
        //     count: values.count,
        //     skuId: currentSku.SKUId,
        //     storeId: productSku.goodsInfo.storeId,
        // }

        let formData = new FormData();
        fileList.forEach((file) => {
            formData.append('file', file);
        });
        formData.append('goodsId',values.goodsId)
        formData.append('count',values.count)
        formData.append('skuId',currentSku.SKUId)
        formData.append('storeId',productSku.goodsInfo.storeId)
        this.setState({loading:true}); // You can use any AJAX library you like

        fetch(React.$BaseUrl + '/admin/goodsEvaluation/brushPraise', {
            method: "post",
            headers: {
                RSnetToken: sessionStorage.getItem('RSnetToken')
            },
            body: formData,
        })
            .then((res) => {
                res.json().then(res => {
                    if (res.code === 0) {
                        this.setState({fileList: []})
                        message.success('添加成功')
                        this.props.history.go(-1);
                        // handleCancel()
                        // } else if (res.data === null) {
                        //     // setFileList([]);
                        //     this.setState({fileList:[]})
                        //     message.error("文件内容异常，请检查文件重新上传");
                        // } else {
                    } else {
                        message.error(res.codeMessage)
                    }
                })
            })
            .catch((res) => {
                console.log(res);
                message.error('上传失败.');
            })
            .finally(() => {
                this.setState({loading:false});
                // setUploading(false);
            });
    }

    onDownload(url) {
        const eleLink = document.createElement('a');
        eleLink.style.display = 'none';
        // eleLink.target = "_blank"
        eleLink.href = url;
        // eleLink.download = url;
        // eleLink.href = record;
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    }

    render() {
        const {fileList, goodsList, productSku, currentSku, loading} = this.state;
        let filedata = {
            accept: ".xls,.xlsx,application/vnd.ms-excel",
            maxCount: 1,
            onRemove: (file) => {
                const index = fileList.indexOf(file);
                const newFileList = fileList.slice();
                newFileList.splice(index, 1);
                this.setState({
                    fileList: newFileList
                })
            },
            beforeUpload: (file) => {
                this.setState({
                    fileList: [file]
                })
                return false;
            },
            fileList,
        };
        return (
            <div className="p-layout-box adopt-editor-box">
                <div>
                    <GoBack history={this.props.history} title="添加评价"/>
                </div>
                <div className="p-layout-content">
                    <Form
                        ref={ref => this.formRef = ref}
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 12,
                        }}
                        onFinish={(values) => this.onFinish(values)}
                        autoComplete="off"
                    >
                        <Form.Item rules={[{required: true}]} label="评价条数" name="count"
                                  >
                            <InputNumber style={{width: 400}}  placeholder="请添加条数" />
                        </Form.Item>
                        <Form.Item rules={[{required: true}]} label="选择商品" name="goodsId">
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => this.selectFilter(input, option)}
                                style={{
                                    width: 400,
                                }}
                                onChange={(e, obj) => this.goodsChange(e, obj)}
                                placeholder="请选择商品"
                            >
                                {
                                    goodsList.map(item => <Option option={item} key={item.goodsId}
                                                                  value={item.goodsId}>{item.goodsName}</Option>)
                                }
                            </Select>
                        </Form.Item>
                        {
                            productSku.hasOwnProperty('goodsInfo') ?
                                <Form.Item
                                    wrapperCol={{
                                        offset: 4,
                                        span: 16,
                                    }}
                                >
                                    <div className='goodsDesc'>
                                        <div className='info'>
                                            <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''}
                                                 alt="商品图片" className='goodsImg'/>
                                            <div className="goodsInfo">
                                                <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                                <div className='price'>
                                                    价格：<React.$Price price={currentSku.skuCurrentPrice}/>&nbsp;&nbsp;
                                                    <React.$Price price={currentSku.skuOriginalPrice} del={true}/>
                                                </div>
                                                <div className='stock'>
                                                    库存：{currentSku.stock}
                                                </div>
                                            </div>
                                        </div>
                                        <div className='goodsSku'>
                                            {
                                                productSku.skuInfo.map(item =>
                                                    <Tag className='tag' key={item.SKUId}
                                                         color={item.SKUId === currentSku.SKUId ? "cyan" : ''}
                                                         onClick={() => this.triggerSkuTag(item)}>
                                                        {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                    </Tag>
                                                )
                                            }

                                        </div>
                                    </div>
                                </Form.Item> : null
                        }
                        <Form.Item label="下载模板" name="downFile">
                            <TheButton type="default" size="middle" onClick={() => {
                                this.onDownload("https://hqmimage.oss-cn-beijing.aliyuncs.com/%E5%95%86%E5%93%81%E8%AF%84%E4%BB%B7.xlsx")
                            }}>
                                下载EXCEL模板
                            </TheButton>
                        </Form.Item>
                        <Form.Item rules={[{required: true}]} label="上传Excel" name="upFiles">
                            <Upload {...filedata}>
                                <Button icon={<UploadOutlined/>}>选择文件</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 4,
                                span: 16,
                            }}
                        >
                            <Space>
                                <Button onClick={() => this.props.history.goBack()}>取消</Button>
                                <Button loading={loading} htmlType="submit" type="primary">提交</Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        );
    }
}

export default Add;
